/*
** Copyright @ 2020 Joshua Branson <jbranso@dismail.de>
**
** This program is free software; you can redistribute it and/or modify it
** under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 3 of the License, or (at
** your option) any later version.
**
** It is distributed in the hope that it will be useful, but
** WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>  //abs
#include <string.h>
#include <errno.h>

FILE * maybe_open_file ()
{
  extern char fileName [];
  extern char * program_invocation_short_name;
  FILE * stream;
  if (strlen (fileName) > 0)
    {
      if ((stream = fopen (fileName, "r")) == NULL)
        {
          fprintf (stderr, "%s: Couldn't open file %s; %s\n",
                   program_invocation_short_name, fileName, strerror (errno));
          exit (EXIT_FAILURE);
        }
      else
        return stream; 
    }
  else
    return stdin;
}

/* This function decrypts letters.
   print_shift('a', 1) -> 'b'
   print_shift('B', 1) -> 'C'
*/
void print_shifted (int shift, int c)
{
  unsigned int lower, upper; // upper is 'a' or 'A', and lower is 'z' or 'Z'
  if (isupper (c))
    {
      lower = 'A'; 
      upper = 'Z'; 
    }
  else
    {
      lower = 'a'; 
      upper = 'z'; 
    }
  // if we add the shift, and the resulting char is not a letter, then
  // we need to do tweak things.
  c += shift; 
  if ( abs (c) > upper ) 
    c = lower + (c - (upper + 1)); 
  putchar (c);  
}

void encrypt (int shift, FILE * stream)
{
  char c;  /* If I make this a char c, then 'z' + 7 = -128 */
  while ((c = getc(stream)) != EOF)
    //if the char is NOT a letter, then print it.
    (!(isalpha (c))) ? putchar(c) : print_shifted(shift, c);
}
